﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using System.Web.UI.WebControls;
using DCH.Models;
using System.Text.RegularExpressions;

namespace DCH.Areas.Admin.Controllers
{ [Authorize]  
    public class RegisterController : Controller
    {
        private DbConnection db = new DbConnection();

        //
        // GET: /Admin/Register/

        public ActionResult Index()
        {
            ViewBag.Player = db.Registers.Where(reg => reg.CaptainName == null).OrderByDescending(reg=>reg.Payment).ToList();
            return View(db.Registers.Where(reg => reg.PlayerName == null).OrderByDescending(reg => reg.Payment).ToList());
        }
        [HttpPost]
        public ActionResult Index(string searchStr, string type)
        {
            if (String.IsNullOrEmpty(searchStr))
                RedirectToAction("Index");
                        int IDint = 0;
            if(Regex.IsMatch(searchStr, @"\d+"))
             IDint = Convert.ToInt32( Regex.Match(searchStr, @"\d+").Value);
           
                ViewBag.Player = db.Registers.Where(reg => reg.CaptainName == null && (reg.PlayerSkill.Contains(searchStr) || reg.City.Contains(searchStr) || reg.PlayerName.Contains(searchStr) || reg.Email.Contains(searchStr) || reg.ID.Equals(IDint) || reg.Phone.Contains(searchStr) || reg.City.Contains(searchStr) || reg.State.Contains(searchStr))).OrderByDescending(reg => reg.Payment).ToList();
                return View(db.Registers.Where(reg => reg.PlayerName == null && (reg.CaptainName.Contains(searchStr) || reg.City.Contains(searchStr) || reg.ClubName.Contains(searchStr) || reg.Email.Contains(searchStr) || reg.ID.Equals(IDint) || reg.Phone.Contains(searchStr) || reg.City.Contains(searchStr) || reg.State.Contains(searchStr))).OrderByDescending(reg => reg.Payment).ToList());
           

        }

        //
        // GET: /Admin/Register/Details/5

        public ActionResult Details(int id = 0)
        {
            Register register = db.Registers.Find(id);
            if (register == null)
            {
                return HttpNotFound();
            }
            return View(register);
        }

        //
        // GET: /Admin/Register/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Admin/Register/Create
    [AllowAnonymous]
        [HttpPost]
        public ActionResult Create(Register register)
        {
            if (ModelState.IsValid)
            {
                Register registered = db.Registers.Where(re => re.Phone == register.Phone).FirstOrDefault();
                if (registered == null)
                {
                    db.Registers.Add(register);
                    db.SaveChanges();

                    SendEmailtoAdmin(register);
                    SendEmailtoUser(register);
                    var ID = string.Empty;
                    var MemberID = string.Empty;
                    switch (register.ID.ToString().Length)
                    {
                        case 1:
                            ID = "00" + register.ID.ToString();
                            break;
                        case 2:
                            ID = "0" + register.ID.ToString();
                            break;
                        default:
                            ID = register.ID.ToString();
                            break;
                    }

                    if (register.State.Substring(0, 3).ToLower().Contains("pun"))
                    {
                        if (register.PlayerName == null)
                        { MemberID = "PBT" + ID; }
                        else
                        { MemberID = "PBI" + ID; }
                    }
                    else
                    {
                        if (register.PlayerName == null)
                        { MemberID = "HRT" + ID; }
                        else
                        { MemberID = "HRI" + ID; }

                    }

                    return RedirectToAction("LastStep", "register", new { id = MemberID });
                }
                else
                {
                    TempData["ErrorMessage"] = "This phone number is already exist.";
                    return RedirectToAction("register", "Home");
                }
            }
            return RedirectToAction("register", "Home", register);
        }

        //
        // GET: /Admin/Register/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Register register = db.Registers.Find(id);
            if (register == null)
            {
                return HttpNotFound();
            }
            return View(register);
        }

        //
        // POST: /Admin/Register/Edit/5

        [HttpPost]
        public ActionResult Edit(Register register)
        {
            if (ModelState.IsValid)
            {
                db.Entry(register).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(register);
        }
    [AllowAnonymous]
        [HttpPost]
        public ActionResult Transection(Register register)
        {
            Register RegisterMain = db.Registers.Find(register.ID);
            RegisterMain.TransactionNumber = register.TransactionNumber;
            RegisterMain.PaymentType = register.PaymentType;
            db.Entry(RegisterMain).State = EntityState.Modified;
            db.SaveChanges();
            TempData["successMessage"] = "Thanks, Wait for confirmation. We will confirm the transection. After that we will send you confirmation mail.";
            return RedirectToAction("register", "Home", new { area = "" });

            //return View(register);
        }
        public FileResult Download()
        {
            // return new FileStreamResult(new FileStream("<your path>", FileMode.Open), "image/jpeg"); 
            return File(Server.MapPath("~/Images/IMG-20150907-WA0002.jpg"), System.Net.Mime.MediaTypeNames.Application.Octet);
        }
        //
        // GET: /Admin/Register/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Register register = db.Registers.Find(id);
            if (register == null)
            {
                return HttpNotFound();
            }
            return View(register);
        }

        //
        // POST: /Admin/Register/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Register register = db.Registers.Find(id);
            db.Registers.Remove(register);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
        public void SendEmailtoAdmin(Register register)
        {
            MailMessage mailMessage = new MailMessage("info@desicricketheroes.com", "info@desicricketheroes.com");
            mailMessage.Subject = "New Team Registered";
            if (register.ClubName != "")
            {
                mailMessage.Subject = "New Team Registered : " + register.ClubName;
                mailMessage.Body = "Hi DCH, Congratulations \n\r  Just now a new team has registered with us.\n\rPlease check details below: \n\r Club Name: " + register.ClubName + "\n\r Captain Name: " + register.CaptainName + " \n\r Phone number: " + register.Phone + " \n\r Email :" + register.Email + "\n\r Team SQUA: " + register.PlayerSquad + "\n\r State: " + register.State + "\n\r City : " + register.City + "  \n\r\n\r ---DCH ADMIN";
            }
            else
            {
                mailMessage.Subject = "New Player Registered : " + register.PlayerName;
                mailMessage.Body = "Hi DCH, Congratulations \n\r  Just now a new Players has registered with us. \n\r Please check details below: \n\r Player Name: " + register.PlayerName + "\n\r Player Skill : " + register.PlayerSkill + " \n\r Phone number: " + register.Phone + " \n\r Email :" + register.Email + "\n\r State: " + register.State + "\n\r City : " + register.City + "  \n\r\n\r ---DCH ADMIN";
            }
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Send(mailMessage);
        }

        public void SendEmailtoUser(Register register)
        {
           
                                                                
            MailMessage mailMessage = new MailMessage("info@desicricketheroes.com", register.Email );
            mailMessage.Subject = "Congrats and Welcome to DCH !";
            mailMessage.Body = "You are now registerd with DesiCricketHeroes.com! \n\r Your Member ID is : " + memberId(register) + "\n\r Your registartion would be confirmed after payment. Please read instruction to make payment on our website \n\r\n\r\n\r -- DCH Team";
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Send(mailMessage);
        }
        public string memberId(Register register)
        {
            var ID = string.Empty;
            var MemberID = string.Empty;
            switch (register.ID.ToString().Length)
            {
                case 1:
                    ID = "00" + register.ID.ToString();
                    break;
                case 2:
                    ID = "0" + register.ID.ToString();
                    break;
                default:
                    ID = register.ID.ToString();
                    break;
            }

            if (register.State.Substring(0, 3).ToLower().Contains("pun"))
            {
                if (register.PlayerName == null)
                { MemberID = "PBT" + ID; }
                else
                { MemberID = "PBI" + ID; }
            }
            else
            {
                if (register.PlayerName == null)
                { MemberID = "HRT" + ID; }
                else
                { MemberID = "HRI" + ID; }

            }
            return MemberID;
        }
        [AllowAnonymous]
        public ActionResult LastStep(string id, string phoneNumber)
        {
            string sub = id.Substring(3);
            Register register = db.Registers.Find(Convert.ToInt32(sub));
            if (phoneNumber == null)
            {
                ViewBag.Valid = "true";
                return View(register);
            }

            else
            {
                if (register.Phone.Contains(phoneNumber))
                    ViewBag.Valid = "true";
                else
                    ViewBag.Valid = "false";

                return View(register);
            }
        }
        public ActionResult ExportData()
        {
           
            GridView gv = new GridView();
            ViewBag.data = db.Registers.Where(reg => reg.PlayerName == null).ToList();
            DataTable table = new DataTable();
            table.Columns.Add("MemberID", typeof(string));
            table.Columns.Add("Club Name", typeof(string));
            table.Columns.Add("Captain Name", typeof(string));
            table.Columns.Add("Email", typeof(string));
            table.Columns.Add("Phone", typeof(string));
            table.Columns.Add("City", typeof(string));
            table.Columns.Add("State", typeof(string));
            table.Columns.Add("Player 1 Name", typeof(string));
            table.Columns.Add("Player 1 Phone", typeof(string));
            table.Columns.Add("Player 1 City", typeof(string));
            table.Columns.Add("Player 2 Name", typeof(string));
            table.Columns.Add("Player 2 Phone", typeof(string));
            table.Columns.Add("Player 2 City", typeof(string));
            table.Columns.Add("Player 3 Name", typeof(string));
            table.Columns.Add("Player 3 Phone", typeof(string));
            table.Columns.Add("Player 3 City", typeof(string));
            table.Columns.Add("Player 4 Name", typeof(string));
            table.Columns.Add("Player 4 Phone", typeof(string));
            table.Columns.Add("Player 4 City", typeof(string));
            table.Columns.Add("Player 5 Name", typeof(string));
            table.Columns.Add("Player 5 Phone", typeof(string));
            table.Columns.Add("Player 5 City", typeof(string));
            table.Columns.Add("Player 6 Name", typeof(string));
            table.Columns.Add("Player 6 Phone", typeof(string));
            table.Columns.Add("Player 6 City", typeof(string));
            table.Columns.Add("Player 7 Name", typeof(string));
            table.Columns.Add("Player 7 Phone", typeof(string));
            table.Columns.Add("Player 7 City", typeof(string));
            table.Columns.Add("Player 8 Name", typeof(string));
            table.Columns.Add("Player 8 Phone", typeof(string));
            table.Columns.Add("Player 8 City", typeof(string));
            table.Columns.Add("Player 9 Name", typeof(string));
            table.Columns.Add("Player 9 Phone", typeof(string));
            table.Columns.Add("Player 9 City", typeof(string));
            table.Columns.Add("Player 10 Name", typeof(string));
            table.Columns.Add("Player 10 Phone", typeof(string));
            table.Columns.Add("Player 10 City", typeof(string));
            table.Columns.Add("Player 11 Name", typeof(string));
            table.Columns.Add("Player 11 Phone", typeof(string));
            table.Columns.Add("Player 11 City", typeof(string));
            table.Columns.Add("Player 12 Name", typeof(string));
            table.Columns.Add("Player 12 Phone", typeof(string));
            table.Columns.Add("Player 12 City", typeof(string));
            table.Columns.Add("Player 13 Name", typeof(string));
            table.Columns.Add("Player 13 Phone", typeof(string));
            table.Columns.Add("Player 13 City", typeof(string));
            table.Columns.Add("Player 14 Name", typeof(string));
            table.Columns.Add("Player 14 Phone", typeof(string));
            table.Columns.Add("Player 14 City", typeof(string));
            table.Columns.Add("Player 15 Name", typeof(string));
            table.Columns.Add("Player 15 Phone", typeof(string));
            table.Columns.Add("Player 15 City", typeof(string));
            table.Columns.Add("Payment", typeof(string));
            table.Columns.Add("Payment Type", typeof(string));
            table.Columns.Add("Transaction / Reference / Cheque no. ", typeof(string));
            foreach (DCH.Models.Register item in ViewBag.data)
            {
                var payment = string.Empty;
                if (item.Payment == true)
                    payment = "Done";
                else
                    payment = "Pending";
                table.Rows.Add(memberId(item), item.ClubName, item.CaptainName, item.Email, item.Phone, item.City, item.State, item.Player1Name, item.Player1Phone, item.Player1City, item.Player2Name, item.Player2Phone, item.Player2City, item.Player3Name, item.Player3Phone, item.Player3City, item.Player4Name, item.Player4Phone, item.Player4City, item.Player5Name, item.Player5Phone, item.Player5City, item.Player6Name, item.Player6Phone, item.Player6City, item.Player7Name, item.Player7Phone, item.Player7City, item.Player8Name, item.Player8Phone, item.Player8City, item.Player9Name, item.Player9Phone, item.Player9City, item.Player10Name, item.Player10Phone, item.Player10City, item.Player11Name, item.Player11Phone, item.Player11City, item.Player12Name, item.Player12Phone, item.Player12City, item.Player13Name, item.Player13Phone, item.Player13City, item.Player14Name, item.Player14Phone, item.Player14City, item.Player15Name, item.Player15Phone, item.Player15City, payment, item.PaymentType, item.TransactionNumber);
            }
            gv.DataSource = table;
            gv.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=Team.xls");
            Response.ContentType = "application/ms-excel";
            Response.Charset = "";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gv.RenderControl(htw);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();

            return RedirectToAction("index");
        }
        public ActionResult ExportPlayers() 
        {
            GridView gv = new GridView();
            ViewBag.data = db.Registers.Where(reg => reg.ClubName == null).ToList();
            DataTable table = new DataTable();
           
            table.Columns.Add("MemberID", typeof(string));
            table.Columns.Add("Player Name", typeof(string));
            table.Columns.Add("Player Skill", typeof(string));
            table.Columns.Add("Email", typeof(string));
            table.Columns.Add("Phone", typeof(string));
            table.Columns.Add("City", typeof(string));
            table.Columns.Add("State", typeof(string));
            table.Columns.Add("Payment", typeof(string));
            table.Columns.Add("Payment Type", typeof(string));
            table.Columns.Add("Transaction / Reference / Cheque no. ", typeof(string));
            foreach (DCH.Models.Register item in ViewBag.data)
            {
                var payment = string.Empty;
                if (item.Payment == true)
                    payment = "Done";
                else
                    payment = "Pending";
                table.Rows.Add(memberId(item), item.PlayerName, item.PlayerSkill, item.Email, item.Phone, item.City, item.State, payment, item.PaymentType, item.TransactionNumber);

            }
            gv.DataSource = table;
            gv.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=Players.xls");
            Response.ContentType = "application/ms-excel";
            Response.Charset = "";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gv.RenderControl(htw);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
            return RedirectToAction("index");
        }
    }
}